package cn.wolfcode.wolf2w.service.impl;


import cn.wolfcode.wolf2w.domain.Region;
import cn.wolfcode.wolf2w.query.RegionQuery;
import cn.wolfcode.wolf2w.repostiory.RegionRepository;
import cn.wolfcode.wolf2w.service.IRegionService;
import cn.wolfcode.wolf2w.util.DBHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

@Service
public class RegionServiceImpl implements IRegionService {

    @Autowired
    private RegionRepository repository;
    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public Region getOne(String id) {

        return repository.findById(id).orElse(null);
    }

    @Override
    public List<Region> list() {
        return repository.findAll();
    }

    @Override
    public void upDate(Region region) {
        repository.save(region);
    }

    @Override
    public void save(Region region) {
        region.setId("");
        repository.save(region);
    }

    @Override
    public void delete(String id) {
        repository.deleteById(id);
    }

    /**
     * 分页查询
     * @param qo
     * @return
     */
    @Override
    public Page<Region> query(RegionQuery qo) {
        //查询条件对象
        Query query = new Query();

        Pageable pageable = PageRequest.of(qo.getCurrentPage() - 1, qo.getPageSize(),
                Sort.Direction.ASC, "_id");


        return  DBHelper.query(mongoTemplate,Region.class,query,pageable);
    }

    @Override
    public void saveOrUpdate(Region region) {
        if (StringUtils.hasLength(region.getId())){
            this.upDate(region);
        }else {
            this.save(region);
        }
    }

    @Override
    public void changeHotValue(String id, int hot) {
        Region region = this.getOne(id);
        region.setIshot(hot);
        this.upDate(region);
    }

    @Override
    public List<Region> queryHotRegion() {

        return repository.findByIshotOrderBySequenceAsc(Region.STATE_HOT);
    }
}


































































